package fa7.socialcode.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import fa7.socialcode.dao.CategoriaDao;
import fa7.socialcode.model.Categoria;



public class CategoriaDaoJpa implements CategoriaDao {
  private static EntityManagerFactory factory;
  static {
    factory = Persistence.createEntityManagerFactory("socialcode");
  }

  private EntityManager entityManager;

  private EntityManager getEntityManager() {
    if (entityManager == null)
      entityManager = factory.createEntityManager();
    return entityManager;

  }

  public List findCategorias() {
    return getEntityManager().createQuery("from Categoria").getResultList();
  }

  public void removeCategoria(Categoria categoria) {
    getEntityManager().getTransaction().begin();

    getEntityManager().remove(categoria);

    getEntityManager().getTransaction().commit();
  }

  public void removeCategoria(Long id) {
    getEntityManager().getTransaction().begin();

    getEntityManager().remove(findCategoria(id));

    getEntityManager().getTransaction().commit();
  }

  public void saveCategoria(Categoria categoria) {
    getEntityManager().getTransaction().begin();
    if (categoria.getId() != null) {
      getEntityManager().merge(categoria);
    } else {
      getEntityManager().persist(categoria);
    }

    getEntityManager().getTransaction().commit();
  }

  public Categoria findCategoria(Long id) {
    return getEntityManager().find(Categoria.class, id);
  }

}
